package client;

import java.io.IOException;
import java.net.Socket;

import javax.crypto.SecretKey;

import messages.Message;
import messages.ChatMessage;
import util.Network;

public class ClientReadThread implements Runnable {

	private Socket sock;
	private long sessionID;
	private SecretKey key;
	
	public ClientReadThread(Socket sock){
		this.sock = sock;
		sessionID = -1L;
	}
	
	public long getSessionID(){
		return this.sessionID;
	}
	
	public void setSessionID(long sessionID){
		this.sessionID = sessionID;
	}
	
	@Override
	public void run() {
		for(;;){
			try {
				byte[] bytesrcvd = Network.readBytes(sock);
				if(key != null) {
					bytesrcvd = Network.decrypt(key, bytesrcvd);
				}				
				Message msg = Network.unserialize(bytesrcvd);
				this.process(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
	}
	
	public void process(Message msg){
		if(msg instanceof ChatMessage){
			ChatMessage cmsg = (ChatMessage) msg;
			System.out.println(cmsg.getSender() + " : " + cmsg.getMessage());
		}
	}

	public void setKey(SecretKey key) {
		this.key = key;
	}

	public SecretKey getKey() {
		return key;
	}
}
